package com.klun.concDesign.chapterThree;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierDemo {
    public static class Soldier implements Runnable{
        private String soldier;
        private final CyclicBarrier cyclicBarrier;

        public Soldier(String soldier, CyclicBarrier cyclicBarrier) {
            this.soldier = soldier;
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            try {
                // 等待所有的士兵到齐
                cyclicBarrier.await();
                doWork();
                // 等待所有士兵完成工作
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
        void doWork(){
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(soldier+":完成个毛线");
        }
    }
    public static class BarrierRun implements Runnable{
        boolean flag;
        int N;

        public BarrierRun(boolean flag, int n) {
            this.flag = flag;
            N = n;
        }

        @Override
        public void run() {
            if (flag){
                System.out.println(N+"个士兵完成任务");
            }else {
                System.out.println("集个JB");
                flag =true;
            }
        }
    }

    public static void main(String[] args) {
        final int N  = 10 ;
        boolean flag = false;
        CyclicBarrier cyclicBarrier = new CyclicBarrier(N, new BarrierRun(flag, N));
        Thread[] allSoldier  =  new Thread[N];
        for (int i = 0; i < 10; i++) {
            System.out.println("士兵"+i+"报道");
            allSoldier[i] = new Thread(new Soldier("蛋蛋士兵"+i,cyclicBarrier));
            allSoldier[i].start();
        }
        System.out.println("wanchenggongzuo");
    }

}
